package com.zhangxun.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Api
@RestController
@RequestMapping("sys")
public class LogoutController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 退出用户删除用户token和对应的缓存数据
     * @return
     */
    @PostMapping("logout")
    @ApiOperation(value = "退出当前用户登录")
    public ResponseEntity<Boolean> logout(){
        //通过请求上下文对象获取请求对象再获取请求头中的token
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Authorization");
        //通过redis删除用户缓存的token
        Boolean delete = stringRedisTemplate.delete(token);
        return ResponseEntity.ok().body(delete);
    }
}
